import os
from datetime import datetime

from sqlalchemy import *
from sqlalchemy.orm import *

from config import settings
from d_utils.log_utils import MyLogger

logger = MyLogger().get_logger()



from typing import Optional

from sqlmodel import SQLModel, Field
TABLE_PREFIX = "dp_"


# noinspection SpellCheckingInspection
class TableNameMeta(type(SQLModel)):
    def __init__(self, name, bases, dct, *args, **kwargs):
        if "__tablename__" not in dct:  # 只修改没有自定义表名的模型
            self.__tablename__ = f"{TABLE_PREFIX}{name}"
        super().__init__(name, bases, dct)

#与当期会话关联的信息
class Example(SQLModel, table=True, metaclass=TableNameMeta):
    id: int | None = Field(default=None, primary_key=True)
    describe: Optional[str] = Field(default=None,sa_column=Column(Text))
    created_at: Optional[datetime] = Field(default=datetime.now())

    pass

class DbInit:
    g_session_local :Optional[sessionmaker] = None

    @classmethod
    def init_db(cls):

        if cls.g_session_local is None:
            password = settings.DB_PASSWORD # 默认值用于本地调试
            host = settings.DB_HOST  # 默认值用于本地调试
            # src/db/db_init.py
            import urllib.parse
            password = urllib.parse.quote_plus(password)
            db_url = f"mysql+pymysql://root:{password}@{host}:{settings.DB_PORT}/{settings.DB_NAME}?charset=utf8mb4"
            logger.info(f"database url: {db_url}")
            # DATABASE_URL = f"mysql+pymysql://ai_strategy:{password}@rm-bp1xw995ve8oa8orzyo.mysql.rds.aliyuncs.com:3306/ai_strategy?charset=utf8mb4"
            DATABASE_URL = db_url
            # 创建数据库
            engine: Engine = create_engine(DATABASE_URL)
            SQLModel.metadata.create_all(engine)

            cls.g_session_local = sessionmaker(autocommit=False, autoflush=False, bind=engine)
            logger.info(f"init db success {cls.g_session_local}")



if __name__ == '__main__':
    DbInit.init_db()
    session = DbInit.g_session_local()
    print(session)